<template>
  <div>
    <NormalForm :enumOpt="enumOpt" :formList="formList" :operateForm="queryForm" pageTitle="属性分析"
                @handleQuery="handleQuery" @handleReset="handleReset" @selectDateType="selectDateType"
    ></NormalForm>
    <!-- 客群分布 -->
    <div class="mainBox">
      <!--图表区 -->
      <div class="bodyBox">
        <div class="chartItem" style="margin-right: 8px">
          <div class="smallLine">
            <div class="line"></div>
            <div class="text">性别分布</div>
          </div>
          <div id="chartOne" class="chartBox"></div>
        </div>
        <div class="chartItem" style="margin-left: 8px">
          <div class="smallLine">
            <div class="line"></div>
            <div class="text">年龄分布</div>
          </div>
          <div id="chartTwo" class="chartBox"></div>
        </div>
      </div>
      <div class="bodyBox">
        <div class="chartItem" style="width: 35%; margin-right: 8px">
          <div class="smallLine">
            <div class="line"></div>
            <div class="text">购买能力</div>
          </div>
          <div id="chartThree" class="chartBox"></div>
        </div>
        <div class="chartItem" style="width: 65%; margin-left: 8px">
          <div class="smallLine">
            <div class="line"></div>
            <div class="text">家庭结构</div>
          </div>
          <div>
            <div class="firstLevel" style="margin-bottom: -20px">
              <div class="itemBox" style="border-top: 4px solid #3072fc">有父母 38%</div>
              <div class="circle"></div>
              <div class="line"></div>
              <div class="circle"></div>
              <div class="itemBox" style="border-top: 4px solid #ff587d">有子女 45.9%</div>
            </div>
            <div class="uprightLine" style="margin: 0 auto"></div>
            <div class="circle" style="margin: 0 auto"></div>
            <div class="itemBox" style="margin: 0 auto; border-top: 4px solid #082aff"></div>
            <div class="circle" style="margin: 0 auto"></div>
            <div class="uprightLine" style="margin: 0 auto"></div>
            <div class="firstLevel" style="margin-top: -20px">
              <div class="itemBox" style="border-top: 4px solid #ffad3a">有配偶 87.65%</div>
              <div class="circle"></div>
              <div class="line"></div>
              <div class="circle"></div>
              <div class="itemBox" style="border-top: 4px solid #14d595">个人 12.35%</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getAllWeUser } from '@/api/customer/customerManage'
import { parseTime } from '@/utils/common'
import * as echarts from 'echarts'
import { getCustomerAge, getCustomerBuy } from '@/api/customerInsight/attributeAnalysis'

export default {
  data() {
    return {
      queryForm: {
        dateType: '0',
        dateRange: null,
        deptId: null,
        createCode: null,
        insuranceType: null
      },
      formList: [
        {
          label: '渠道',
          value: '',
          prop: 'insuranceType',
          type: 'SELECT',
          emunName: 'insuranceList'
        },
        {
          label: '管理机构',
          value: null,
          prop: 'deptId',
          type: 'MANAGE_COM',
          emunName: ''
        },
        {
          label: '创建人',
          value: '',
          prop: 'createCode',
          type: 'SELECT',
          emunName: 'creatorList'
        },
        {
          label: '',
          value: '',
          prop: 'dateType',
          type: 'SPECIAL_SELECT',
          emunName: 'dateTypeList'
        },
        {
          label: '',
          value: null,
          prop: 'dateRange',
          type: 'SPECIAL_DATE',
          emunName: '',
          aboutProp: 'dateType',
          pickerOptions: {
            disabledDate(time) {
              return time.getTime() > Date.now()
            }
          }
        }
      ],
      enumOpt: {
        insuranceList: [],
        creatorList: [],
        dateTypeList: [
          { dictLabel: '自然日', dictValue: '0' },
          { dictLabel: '自然周', dictValue: '1' },
          { dictLabel: '自然月', dictValue: '2' },
          { dictLabel: '自然年', dictValue: '3' }
        ]
      },
      loading: false
    }
  },
  watch: {
    'queryForm.deptId': {
      handler() {
        if (this.queryForm.deptId) this.getAllWeUserInfo()
      }
    }
  },
  created() {
    this.getLabelList()
    this.selectDateType()
    this.handleQuery()
  },
  methods: {
    getLabelList() {
      // 渠道
      this.getDicts('insurance_type').then((res) => {
        if (res.code === 200) {
          this.enumOpt.insuranceList = res.data
        }
      })
    },
    getAllWeUserInfo() {
      this.enumOpt.creatorList = []
      const params = {
        deptId: this.queryForm.deptId,
        userName: ''
      }
      getAllWeUser(params).then(res => {
        if (res.code === 200) {
          res.data.forEach(item => {
            this.enumOpt.creatorList.push({
              dictLabel: item.userName,
              dictValue: item.userId
            })
          })
        }
      })
    },
    selectDateType() {
      let startTime = parseTime(new Date(new Date().getTime() - 3600 * 1000 * 24 * 7), '{y}-{m}-{d}')
      let endTime = parseTime(new Date(new Date().getTime()), '{y}-{m}-{d}')
      if (this.queryForm.dateType === '0') {
        this.queryForm.dateRange = [startTime, endTime]
      } else {
        this.queryForm.dateRange = startTime
      }
    },
    async getCustomerSex(params) {
      // const res=await getCustomerSex(params)
      // if(res.code===200){
      //   let sexData=[]
      //   sexData.push({name:'男性',value:res.data.totalNum?(res.data.man/res.data.totalNum*100).toFixed(2):0})
      //   sexData.push({name:'女性',value:res.data.totalNum?(res.data.woman/res.data.totalNum*100).toFixed(2):0})
      //   console.log(sexData);
      //   this.getChartOne(sexData)
      // }
      const sexData = [{
        'name': '女性占比',
        'value': '53.45'
      },
        {
          'name': '男性占比',
          'value': '44.65'
        },
        {
          'name': '未知性别占比',
          'value': '1.9'
        }]
      window.setTimeout(() => {
        this.getChartOne(sexData)
      }, 100)
    },
    async getCustomerAge(params) {
      // const res = await getCustomerAge(params)
      // if (res.code === 200) {
      //   let ageData = []
      //   ageData.push({
      //     name: '18-24',
      //     value: res.data.totalAge ? (res.data.ageEightTeen / res.data.totalAge * 100).toFixed(2) : 0
      //   })
      //   ageData.push({
      //     name: '25-30',
      //     value: res.data.totalAge ? (res.data.ageTwentyFive / res.data.totalAge * 100).toFixed(2) : 0
      //   })
      //   ageData.push({
      //     name: '31-35',
      //     value: res.data.totalAge ? (res.data.ageThirtyOne / res.data.totalAge * 100).toFixed(2) : 0
      //   })
      //   ageData.push({
      //     name: '36-40',
      //     value: res.data.totalAge ? (res.data.ageThirtySix / res.data.totalAge * 100).toFixed(2) : 0
      //   })
      //   ageData.push({
      //     name: '41-45',
      //     value: res.data.totalAge ? (res.data.ageFortyOne / res.data.totalAge * 100).toFixed(2) : 0
      //   })
      //   ageData.push({
      //     name: '46-50',
      //     value: res.data.totalAge ? (res.data.ageFortySix / res.data.totalAge * 100).toFixed(2) : 0
      //   })
      //   ageData.push({
      //     name: '51-55',
      //     value: res.data.totalAge ? (res.data.ageFiftyOne / res.data.totalAge * 100).toFixed(2) : 0
      //   })
      //   ageData.push({
      //     name: '56-60',
      //     value: res.data.totalAge ? (res.data.ageFiftySix / res.data.totalAge * 100).toFixed(2) : 0
      //   })
      //   ageData.push({
      //     name: '61-65',
      //     value: res.data.totalAge ? (res.data.ageSixtyOne / res.data.totalAge * 100).toFixed(2) : 0
      //   })
      //   ageData.push({
      //     name: '65+',
      //     value: res.data.totalAge ? (res.data.ageSixtyFive / res.data.totalAge * 100).toFixed(2) : 0
      //   })
      //   console.log(ageData)
      //   this.getChartTwo(ageData)
      // }
      const agentData = [
        {
          "name": "18-24",
          "value": "4.35"
        },
        {
          "name": "25-30",
          "value": "6.48"
        },
        {
          "name": "31-35",
          "value": "8.69"
        },
        {
          "name": "36-40",
          "value": "11.43"
        },
        {
          "name": "41-45",
          "value": "26.33"
        },
        {
          "name": "46-50",
          "value": "24.37"
        },
        {
          "name": "51-55",
          "value": "8.73"
        },
        {
          "name": "56-60",
          "value": "4.73"
        },
        {
          "name": "61-65",
          "value": "3.7"
        },
        {
          "name": "65+",
          "value": "1.19"
        }
      ]
      window.setTimeout(() => {
        this.getChartTwo(agentData)
      }, 100)
    },
    async getCustomerBuy(params) {
      // const res = await getCustomerBuy(params)
      // if (res.code === 200) {
      //   let buyData = []
      //   buyData.push({
      //     name: '高消费',
      //     value: res.data.totalNum ? (res.data.high / res.data.totalNum * 100).toFixed(2) : 0
      //   })
      //   buyData.push({
      //     name: '中消费',
      //     value: res.data.totalNum ? (res.data.mid / res.data.totalNum * 100).toFixed(2) : 0
      //   })
      //   buyData.push({
      //     name: '低消费',
      //     value: res.data.totalNum ? (res.data.low / res.data.totalNum * 100).toFixed(2) : 0
      //   })
      //   console.log(buyData, res.data.high / res.data.totalNum)
      //   this.getChartThree(buyData)
      // }
      const buyData = [
        {
          "name": "高消费",
          "value": "6.29"
        },
        {
          "name": "中消费",
          "value": "55.31"
        },
        {
          "name": "低消费",
          "value": "38.4"
        }
      ]
      window.setTimeout(() => {
          this.getChartThree(buyData)
      }, 100)
    },
    handleQuery() {
      this.loading = true
      let obj = this.reassembly()
      const params = {
        dateType: obj.dateType,
        startDate: obj.startTime,
        endDate: obj.endTime,
        deptId: this.queryForm.deptId ? [this.queryForm.deptId] : [],
        userId: this.queryForm.createCode || '',
        insuranceType: this.queryForm.insuranceType || ''
      }
      Promise.all([
        this.getCustomerSex(params),
        this.getCustomerAge(params),
        this.getCustomerBuy(params)
      ])
    },
    handleReset() {
      let startTime = parseTime(new Date(new Date().getTime() - 3600 * 1000 * 24 * 7), '{y}-{m}-{d}')
      let endTime = parseTime(new Date(new Date().getTime()), '{y}-{m}-{d}')
      this.enumOpt.creatorList = []
      this.queryForm = {
        dateType: '0',
        dateRange: [startTime, endTime],
        deptId: null,
        createCode: null,
        insuranceType: null
      }
      this.handleQuery()
    },
    // 组装startTime和endTime入参
    reassembly() {
      let startTime = null, endTime = null, dateType = null
      let selectDate = this.queryForm.dateRange
      if (selectDate) {
        if (this.queryForm.dateType === '0') {
          dateType = 'DAY' // 日
          startTime = selectDate[0]
          endTime = selectDate[1]
        } else if (this.queryForm.dateType === '1') {
          dateType = 'DAY' // 周
          startTime = parseTime(new Date(new Date(selectDate).getTime() - 24 * 60 * 60 * 1000), '{y}-{m}-{d}')
          endTime = parseTime(new Date(new Date(selectDate).getTime() + 5 * 24 * 60 * 60 * 1000), '{y}-{m}-{d}')
        } else if (this.queryForm.dateType === '2') {
          dateType = 'MONTH' // 月
          startTime = selectDate
          const temp = selectDate.split('-')
          let str = +temp[1] + 1
          temp[1] = temp[1] < 9 ? '0' + str : str
          if (temp[1] === 13) {
            temp[1] = '01'
            temp[0] = +temp[0] + 1
          }
          endTime = temp.join('-')
        } else if (this.queryForm.dateType === '3') {
          dateType = 'YEAR' // 年
          startTime = selectDate
          const temp = selectDate.split('-')
          temp[0] = +temp[0] + 1
          endTime = temp.join('-')
        }
      }
      return { startTime, endTime, dateType }
    },
    // 图表
    getChartOne(sexData) {
      var mycharts = echarts.init(document.getElementById('chartOne'))
      var option = {
        color: ['#FFAD3A', '#082aff', '#FAC8BC'],
        tooltip: {
          trigger: 'item',
          textStyle: { fontSize: 16 },
          formatter: '{b}\n{c}% '
        },
        legend: { textStyle: { color: '#ffffff' }, show: false },
        series: {
          type: 'pie',
          center: ['50%', '50%'],
          radius: ['40%', '60%'],
          showEmptyCircle: true,
          label: { formatter: '{b}\n{c}% ', color: '#082aff ', fontSize: 14 },
          data: sexData,
          labelLine: {
            lineStyle: {
              type: 'dashed',
              color: '#CCCCCC'
            }
          }
        }
      }
      mycharts.setOption(option)
    },
    getChartTwo(ageData) {
      var mycharts = echarts.init(document.getElementById('chartTwo'))
      var option = {
        color: [
          '#FC876A',
          '#082aff',
          '#FFF3EB',
          '#FFE5D3',
          '#FAC8BC',
          '#FFBAA2',
          '#FFAD3A',
          '#FFE8C9',
          '#FFD08E'
        ],
        tooltip: {
          trigger: 'item',
          textStyle: { fontSize: 16 },
          formatter: '{b}\n{c}% '
        },
        legend: { textStyle: { color: '#ffffff' }, show: false },
        series: {
          type: 'pie',
          center: ['50%', '50%'],
          radius: ['40%', '60%'],
          showEmptyCircle: true,
          label: { formatter: '{b}\n{c}% ', color: '#082aff ', fontSize: 14 },
          data: ageData,
          labelLine: {
            lineStyle: {
              type: 'dashed',
              color: '#CCCCCC'
            }
          }
        }
      }
      mycharts.setOption(option)
    },
    getChartThree(buyData) {
      var mycharts = echarts.init(document.getElementById('chartThree'))
      var option = {
        color: ['#FFAD3A', '#FFE8C9', '#FFD08E'],
        tooltip: {
          trigger: 'item',
          textStyle: { fontSize: 16 },
          formatter: '{b}\n{c}% '
        },
        legend: { textStyle: { color: '#ffffff' }, show: false },
        series: {
          type: 'pie',
          center: ['50%', '50%'],
          radius: ['40%', '60%'],
          showEmptyCircle: true,

          label: { formatter: '{b}\n{c}%', color: '#082aff ', fontSize: 14 },
          data: buyData,
          labelLine: {
            lineStyle: {
              type: 'dashed',
              color: '#CCCCCC'
            }
          }
        }
      }
      mycharts.setOption(option)
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/element-ui.scss";
@import "@/styles/base.scss";

.mainBox {
  margin-top: 20px;
  width: 100%;
  background: #ffffff;
  border-radius: 8px;
  padding: 16px 20px;

  .bodyBox {
    width: 100%;
    display: flex;
    margin-bottom: 20px;

    .chartItem {
      width: 50%;
      border: 1px solid #eeeeee;
      box-sizing: border-box;
    }

    .chartBox {
      flex: 1;
      height: 400px;
      box-sizing: border-box;
    }

    .smallLine {
      display: flex;
      align-items: center;
      margin: 20px 0;

      .line {
        width: 3px;
        height: 16px;
        background: #082aff;
      }

      .text {
        margin-left: 10px;
      }
    }

    .firstLevel {
      width: 480px;
      margin: 0 auto;
      display: flex;
      align-items: center;

      .line {
        width: 216px;
        height: 1px;
        border: 1px solid #cccccc;
      }
    }

    .itemBox {
      width: 103px;
      height: 42px;
      background: #ffffff;
      box-shadow: 0px 2px 10px 0px rgba(216, 216, 216, 0.5);
      border-radius: 4px;
      line-height: 38px;
      text-align: center;
    }

    .circle {
      width: 11px;
      height: 11px;
      background: #ffffff;
      border: 1px solid #cccccc;
      border-radius: 50%;
    }

    .uprightLine {
      width: 2px;
      height: 66px;
      border: 1px solid #cccccc;
    }
  }

}

#chartFive {
  width: 100%;
  height: 300px;
}

#chartSix {
  width: 100%;
  height: 300px;
}

</style>
